import { defineComponent, ref, reactive, onMounted, onUnmounted } from "vue";
import TablePage from "@/components/TablePage/TablePage";
import { tablesInterface } from "@/common/interface/table.interface";
import MusicApkService from "./index.service";
import to from "await-to-js";
import { message } from "ant-design-vue";
import styles from "./index.module.less";
import Add from "./Add/Add";
import { MobileOutlined, TabletOutlined } from "@ant-design/icons-vue";
const StatusSwitch = defineComponent({
  props: {
    record: {
      type: Object,
    },
    value: {
      type: Number,
    }
  },
  emits: ["change"],
  setup(props: any, { emit }) {
    const musicApkService = new MusicApkService();
    const loading = ref(false);
    const statusChange = async (e) => {
      loading.value = true;
      const [err, res]: any = await to(musicApkService.statusChange({
        record: props.record,
        status: e,
      }));
      if (!err) {
        e === 0 ? message.success("开启成功!") : message.success("关闭成功!");
        emit("change");
      }
      loading.value = false;
    }
    return () => <a-switch loading={loading.value} checked={props.value} checkedValue={0} unCheckedValue={1} onChange={(e) => { statusChange(e) }} />
  }
})

export default defineComponent({
  name: "List",
  setup() {
    const tablePageRef = ref(null as any);
    const musicApkService = new MusicApkService();
    // 表格定义
    const tables = reactive({
      list: [
        {
          title: "apk版本管理",
          rowKey: "id",
          columns: [
            {
              title: "ID",
              dataIndex: "id",
              align: "center",
              width: "80px",
            },
            {
              title: "设备类型",
              dataIndex: "platform",
              align: "center",
              width: "180px",
            },
            {
              title: "版本名",
              dataIndex: "versionName",
              align: "center",
              width: "220px",
            },
            {
              title: "版本号",
              dataIndex: "versionCode",
              align: "center",
              width: "220px",
            },
            {
              title: "文件地址",
              dataIndex: "file",
              align: "center",
              width: "280px",
            },
            {
              title: "排序",
              dataIndex: "sort",
              align: "center",
              width: "180px",
            },
            {
              title: "状态",
              dataIndex: "status",
              align: "center",
              width: "180px",
            },
            {
              title: "备注",
              dataIndex: "remark",
              align: "center",
              width: "280px",
            },
            {
              title: "创建时间",
              dataIndex: "createTime",
              align: "center",
              width: "280px",
            },
            {
              title: "修改时间",
              dataIndex: "updateTime",
              align: "center",
              width: "280px",
            }
          ],
          toolbar: {
            left: ["refresh", "add"],
            right: ["filter", "search"],
            add: {
              permissions: "music:apk:add",
              handler: () => {
                const addPopupRef = tablePageRef.value.getPopup("addRef");
                addPopupRef.value.open({ type: 'add' });
              }
            },
          },
          searchForm: {
            versionName: {
              type: "input",
              label: "版本名",
              attrs: { placeholder: "版本名", allowClear: true },
            },
            versionCode: {
              type: "input",
              label: "版本号",
              attrs: { placeholder: "版本号", allowClear: true },
            },
            status: {
              type: "select",
              label: "状态",
              attrs: { placeholder: "状态", allowClear: true },
              datas: [{ label: "开启", value: 0 }, { label: "关闭", value: 1 }],
            },
          },
          service: musicApkService,
          operation: ({ record }) => [
            {
              type: "edit",
              permissions: "music:apk:edit",
              clickHandler: () => {
                const addPopupRef = tablePageRef.value.getPopup("addRef");
                addPopupRef.value.open({ type: 'edit', id: record.id });
              }
            },
            {
              type: "delete",
              permissions: "music:apk:remove",
              clickHandler: "delete",
            },
          ],
          bodyCell: ({ text, record, index, column }) => {
            if (column.dataIndex === "platform") {
              return <>
                <span class={styles.platform}>
                  {
                    text?.toString() === "0" && <>
                      <TabletOutlined class={styles.platformIcon} />Pad
                    </>
                  }
                  {
                    text?.toString() === "1" && <>
                      <MobileOutlined class={styles.platformIcon} />Phone
                    </>
                  }
                  {
                    text?.toString() === "2" && <>
                      <TabletOutlined class={styles.platformIcon} />Panel
                    </>
                  }
                </span>
              </>
            }
            if (column.dataIndex === "file") {
              return text ? <div class={styles.fileUrl} onClick={() => { downLoadUrl(text, '.apk', record) }}>{text}</div> : <span class={styles.noFile}>暂未上传apk文件</span>
            }
            if (column.dataIndex === "status") {
              return <>
                <StatusSwitch record={record} value={Number(text)} />
              </>
            }
          },
          popups: [
            {
              ref: "addRef",
              dom: () => <Add onChange={() => { tablePageRef.value.reload() }} />,
            }
          ],
          pagination: true,
          tableSourceFormat: {
            data: 'rows',
            pageSize: 'pageSize',
            current: 'pageNum',
          },
        }
      ],
    } as tablesInterface)
    // 配置项
    const config = reactive({
      table: tables.list[0],
    })
    // 下载文件
    const downLoadUrl = async (file_url: string, fileExtension: string, record: any) => {
      const [err, res] = await to(fetch(file_url));
      if (!err) {
        const blob = await res?.blob();
        // 创建一个指向Blob对象的URL
        const url = window.URL.createObjectURL(blob as any);
        // 创建一个隐藏的<a>元素
        const a = document.createElement('a');
        a.style.display = 'none';
        // 设置<a>元素的href属性为Blob对象的URL
        a.href = url;
        // 设置下载的文件名（可选，这里使用URL的最后一部分作为文件名）
        const filename = file_url.split('/').pop();
        a.download = filename || `untitled${fileExtension}`;
        // 将<a>元素添加到文档中（虽然它是隐藏的）
        document.body.appendChild(a);
        // 触发<a>元素的点击事件以下载文件
        a.click();
        // 释放URL对象（不再需要时）
        window.URL.revokeObjectURL(url);
      }
    }
    return () => (
      <TablePage ref={tablePageRef} config={config} />
    )
  }
})